﻿using System;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using LeanEngine.Data.Linq.Language;

namespace LeanEngine.Data.Linq.Translator
{
    internal abstract class LinqTranslator<T>
        where T : class
    {
        #region PropertyInfo Members

        protected List<TableToken> Tables { get; set; }

        #endregion

        #region Abstract Members

        internal abstract bool CanEvaluate(QueryContext context);
        internal abstract T Interpret(QueryContext context);

        #endregion

        #region Virtual Method Members

        protected virtual Expression Evaluate(Expression exp)
        {
            if (exp == null) return exp;

            switch (exp.NodeType)
            {
                #region Binary Expression
                case ExpressionType.Add:
                case ExpressionType.AddChecked:
                case ExpressionType.And:
                case ExpressionType.AndAlso:
                case ExpressionType.ArrayIndex:
                case ExpressionType.Coalesce:
                case ExpressionType.Divide:
                case ExpressionType.Equal:
                case ExpressionType.ExclusiveOr:
                case ExpressionType.GreaterThan:
                case ExpressionType.GreaterThanOrEqual:
                case ExpressionType.LeftShift:
                case ExpressionType.LessThan:
                case ExpressionType.LessThanOrEqual:
                case ExpressionType.Modulo:
                case ExpressionType.Multiply:
                case ExpressionType.MultiplyChecked:
                case ExpressionType.NotEqual:
                case ExpressionType.Or:
                case ExpressionType.OrElse:
                case ExpressionType.Power:
                case ExpressionType.RightShift:
                case ExpressionType.Subtract:
                case ExpressionType.SubtractChecked:
                    return EvaluateBinary((BinaryExpression)exp);
                #endregion

                #region Unary Expression
                case ExpressionType.ArrayLength:
                case ExpressionType.Convert:
                case ExpressionType.ConvertChecked:
                case ExpressionType.Negate:
                case ExpressionType.NegateChecked:
                case ExpressionType.Not:
                case ExpressionType.Quote:
                case ExpressionType.TypeAs:
                    return EvaluateUnary((UnaryExpression)exp);
                #endregion

                #region NewArray Expression
                case ExpressionType.NewArrayInit:
                case ExpressionType.NewArrayBounds:
                    return EvaluateNewArray((NewArrayExpression)exp);
                #endregion

                #region Call Expression
                case ExpressionType.Call:
                    return EvaluateMethodCall((MethodCallExpression)exp);
                #endregion

                #region Conditional Expression
                case ExpressionType.Conditional:
                    return EvaluateConditional((ConditionalExpression)exp);
                #endregion

                #region Constant Expression
                case ExpressionType.Constant:
                    return EvaluateConstant((ConstantExpression)exp);
                #endregion

                #region Invoke Expression
                case ExpressionType.Invoke:
                    return EvaluateInvocation((InvocationExpression)exp);
                #endregion

                #region Lambda Expression
                case ExpressionType.Lambda:
                    return EvaluateLambda((LambdaExpression)exp);
                #endregion

                #region ListInit Expression
                case ExpressionType.ListInit:
                    return EvaluateListInit((ListInitExpression)exp);
                #endregion

                #region Member Access Expression
                case ExpressionType.MemberAccess:
                    return EvaluateMemberAccess((MemberExpression)exp);
                #endregion

                #region Member Init Expression
                case ExpressionType.MemberInit:
                    return EvaluateMemberInit((MemberInitExpression)exp);
                #endregion

                #region New Expression
                case ExpressionType.New:
                    return EvaluateNew((NewExpression)exp);
                #endregion

                #region Parameter Expression
                case ExpressionType.Parameter:
                    return EvaluateParameter((ParameterExpression)exp);
                #endregion

                #region TypeIs Expression
                case ExpressionType.TypeIs:
                    return EvaluateTypeIs((TypeBinaryExpression)exp);
                #endregion

                default:
                    throw new ArgumentOutOfRangeException(string.Format("Unhandled expression type: '{0}'", exp.NodeType));
            }
        }

        protected virtual Expression EvaluateBinary(BinaryExpression b)
        {
            Expression left = Evaluate(b.Left);
            Expression right = Evaluate(b.Right);
            
            if ((left == b.Left) && (right == b.Right)) return b;

            return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
        }

        protected virtual MemberBinding EvaluateBinding(MemberBinding binding)
        {
            switch (binding.BindingType)
            {
                case MemberBindingType.Assignment: return EvaluateMemberAssignment((MemberAssignment)binding);
                case MemberBindingType.MemberBinding: return EvaluateMemberMemberBinding((MemberMemberBinding)binding);
                case MemberBindingType.ListBinding: return EvaluateMemberListBinding((MemberListBinding)binding);
                default: throw new ArgumentOutOfRangeException(string.Format("Unhandled binding type '{0}'", binding.BindingType));
            }
        }

        protected virtual IEnumerable<MemberBinding> EvaluateBindingList(ReadOnlyCollection<MemberBinding> original)
        {
            List<MemberBinding> list = null;
            int num = 0x0;
            int count = original.Count;
            while (num < count)
            {
                MemberBinding item = EvaluateBinding(original[num]);
                if (list != null)
                {
                    list.Add(item);
                }
                else if (item != original[num])
                {
                    list = new List<MemberBinding>(count);
                    for (int i = 0; i < num; i++)
                    {
                        list.Add(original[i]);
                    }
                    list.Add(item);
                }
                num++;
            }

            if (list != null)
            {
                return list;
            }

            return original;
        }

        protected virtual Expression EvaluateConditional(ConditionalExpression c)
        {
            Expression test = Evaluate(c.Test);
            Expression ifTrue = Evaluate(c.IfTrue);
            Expression ifFalse = Evaluate(c.IfFalse);
            if (((test == c.Test) && (ifTrue == c.IfTrue)) && (ifFalse == c.IfFalse))
            {
                return c;
            }

            return Expression.Condition(test, ifTrue, ifFalse);
        }

        protected virtual Expression EvaluateConstant(ConstantExpression c)
        {
            return c;
        }

        protected virtual ElementInit EvaluateElementInitializer(ElementInit initializer)
        {
            ReadOnlyCollection<Expression> arguments = EvaluateExpressionList(initializer.Arguments);
            if (arguments != initializer.Arguments)
            {
                return Expression.ElementInit(initializer.AddMethod, arguments);
            }

            return initializer;
        }

        protected virtual IEnumerable<ElementInit> EvaluateElementInitializerList(ReadOnlyCollection<ElementInit> original)
        {
            List<ElementInit> list = null;
            int num = 0;
            int count = original.Count;
            while (num < count)
            {
                ElementInit item = EvaluateElementInitializer(original[num]);
                if (list != null)
                {
                    list.Add(item);
                }
                else if (item != original[num])
                {
                    list = new List<ElementInit>(count);
                    for (int i = 0; i < num; i++)
                    {
                        list.Add(original[i]);
                    }
                    list.Add(item);
                }
                num++;
            }

            if (list != null)
            {
                return list;
            }

            return original;
        }

        protected virtual ReadOnlyCollection<Expression> EvaluateExpressionList(ReadOnlyCollection<Expression> original)
        {
            List<Expression> list = null;
            int num = 0x0;
            int count = original.Count;
            while (num < count)
            {
                Expression item = Evaluate(original[num]);
                if (list != null)
                {
                    list.Add(item);
                }
                else if (item != original[num])
                {
                    list = new List<Expression>(count);
                    for (int i = 0; i < num; i++)
                    {
                        list.Add(original[i]);
                    }
                    list.Add(item);
                }
                num++;
            }

            if (list != null)
            {
                return new ReadOnlyCollection<Expression>(list);
            }

            return original;
        }

        protected virtual Expression EvaluateInvocation(InvocationExpression iv)
        {
            IEnumerable<Expression> arguments = EvaluateExpressionList(iv.Arguments);
            Expression expression = Evaluate(iv.Expression);
            if ((arguments == iv.Arguments) && (expression == iv.Expression))
            {
                return iv;
            }

            return Expression.Invoke(expression, arguments);
        }

        protected virtual Expression EvaluateLambda(LambdaExpression lambda)
        {
            Expression body = Evaluate(lambda.Body);
            if (body != lambda.Body)
            {
                return Expression.Lambda(lambda.Type, body, lambda.Parameters);
            }

            return lambda;
        }

        protected virtual Expression EvaluateListInit(ListInitExpression init)
        {
            NewExpression newExpression = EvaluateNew(init.NewExpression);
            IEnumerable<ElementInit> initializers = EvaluateElementInitializerList(init.Initializers);
            if ((newExpression == init.NewExpression) && (initializers == init.Initializers))
            {
                return init;
            }

            return Expression.ListInit(newExpression, initializers);
        }

        protected virtual Expression EvaluateMemberAccess(MemberExpression m)
        {
            Expression expression = Evaluate(m.Expression);
            if (expression != m.Expression)
            {
                return Expression.MakeMemberAccess(expression, m.Member);
            }

            return m;
        }

        protected virtual MemberAssignment EvaluateMemberAssignment(MemberAssignment assignment)
        {
            Expression expression = Evaluate(assignment.Expression);
            if (expression != assignment.Expression)
            {
                return Expression.Bind(assignment.Member, expression);
            }

            return assignment;
        }

        protected virtual Expression EvaluateMemberInit(MemberInitExpression init)
        {
            NewExpression newExpression = EvaluateNew(init.NewExpression);
            IEnumerable<MemberBinding> bindings = EvaluateBindingList(init.Bindings);
            if ((newExpression == init.NewExpression) && (bindings == init.Bindings))
            {
                return init;
            }

            return Expression.MemberInit(newExpression, bindings);
        }

        protected virtual MemberListBinding EvaluateMemberListBinding(MemberListBinding binding)
        {
            IEnumerable<ElementInit> initializers = EvaluateElementInitializerList(binding.Initializers);
            if (initializers != binding.Initializers)
            {
                return Expression.ListBind(binding.Member, initializers);
            }

            return binding;
        }

        protected virtual MemberMemberBinding EvaluateMemberMemberBinding(MemberMemberBinding binding)
        {
            IEnumerable<MemberBinding> bindings = EvaluateBindingList(binding.Bindings);
            if (bindings != binding.Bindings)
            {
                return Expression.MemberBind(binding.Member, bindings);
            }

            return binding;
        }

        protected virtual Expression EvaluateMethodCall(MethodCallExpression m)
        {
            Expression instance = Evaluate(m.Object);
            IEnumerable<Expression> arguments = EvaluateExpressionList(m.Arguments);
            if ((instance == m.Object) && (arguments == m.Arguments))
            {
                return m;
            }

            return Expression.Call(instance, m.Method, arguments);
        }

        protected virtual NewExpression EvaluateNew(NewExpression nex)
        {
            IEnumerable<Expression> arguments = EvaluateExpressionList(nex.Arguments);
            if (arguments == nex.Arguments)
            {
                return nex;
            }

            if (nex.Members != null)
            {
                return Expression.New(nex.Constructor, arguments, nex.Members);
            }

            return Expression.New(nex.Constructor, arguments);
        }

        protected virtual Expression EvaluateNewArray(NewArrayExpression na)
        {
            IEnumerable<Expression> initializers = EvaluateExpressionList(na.Expressions);
            if (initializers == na.Expressions)
            {
                return na;
            }

            if (na.NodeType == ExpressionType.NewArrayInit)
            {
                return Expression.NewArrayInit(na.Type.GetElementType(), initializers);
            }

            return Expression.NewArrayBounds(na.Type.GetElementType(), initializers);
        }

        protected virtual Expression EvaluateParameter(ParameterExpression p)
        {
            return p;
        }

        protected virtual Expression EvaluateTypeIs(TypeBinaryExpression b)
        {
            Expression expression = Evaluate(b.Expression);
            if (expression != b.Expression)
            {
                return Expression.TypeIs(expression, b.TypeOperand);
            }
            return b;
        }

        protected virtual Expression EvaluateUnary(UnaryExpression u)
        {
            Expression operand = Evaluate(u.Operand);
            if (operand != u.Operand)
            {
                return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method);
            }

            return u;
        }

        #endregion

        #region Static Method Members

        /// <summary>
        /// Check to see if the expression is valid for
        /// Select, Where, OrderBy, ThenBy, OrderByDescending and ThenByDescending
        /// and then return the lmbda section
        /// </summary>
        /// <returns></returns>
        protected static LambdaExpression GetLambdaWithParamCheck(MethodCallExpression mc)
        {
            if (mc.Arguments.Count != 2 || !IsLambda(mc.Arguments[1]))
                return null;

            var lambda = GetLambda(mc.Arguments[1]);
            return (lambda.Parameters.Count != 1) ? null : lambda;
        }

        protected static bool IsLambda(Expression expression)
        {
            return RemoveQuotes(expression).NodeType == ExpressionType.Lambda;
        }

        protected static LambdaExpression GetLambda(Expression expression)
        {
            return RemoveQuotes(expression) as LambdaExpression;
        }

        protected static Expression RemoveQuotes(Expression expression)
        {
            while (expression.NodeType == ExpressionType.Quote)
            {
                expression = ((UnaryExpression)expression).Operand;
            }

            return expression;
        }

        #endregion
    }
}
